package com.xiyoukt.springboot.service.impl;

import com.xiyoukt.springboot.entity.User;
import com.xiyoukt.springboot.mapper.UserMapper;
import com.xiyoukt.springboot.mapper.master.MasterUserMapper;
import com.xiyoukt.springboot.mapper.slave.SlaveUserMapper;
import com.xiyoukt.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

//    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MasterUserMapper masterUserMapper;
    @Autowired
    private SlaveUserMapper slaveUserMapper;

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    @Transactional
    public int addTwoUser(User user) {
        int i = userMapper.addUser(user);
        try{
            int r = 1 / 0;
        }catch (Exception e){
            e.printStackTrace();
            // 不能将异常吃掉，必须抛出一个运行时异常或者其子类，否则事务不会生效
            throw new RuntimeException("error");
        }
        int i1 = userMapper.addUser(user);
        return i + i1;
    }

    @Override
    public List<User> getAll() {
        return userMapper.getAll();
    }

    @Override
    public int delUser(Long id) {
        return userMapper.delUser(id);
    }

    @Override
    public List<User> pageUser(int page, int size) {
        return userMapper.pageUser(page, size);
    }

    @Override
    @Transactional
    public void addTwoDoubleDataSourceUser(User user) {
        // 多数据源环境下，事务只对主数据源有效
        masterUserMapper.addUser(user);
        // 不会回退
        slaveUserMapper.addUser(user);
        if(1 == 1){
            throw new  RuntimeException("error");
        }
    }

    @Override
    public User getUser(Long id) {
        return masterUserMapper.getUser(id);
    }
}
